import { Module } from '@nestjs/common';
// 导入配置模块和服务
import { ConfigModule, ConfigService } from '@nestjs/config';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { MongooseModule } from '@nestjs/mongoose';
import { MailerModule } from '@nestjs-modules/mailer';
import { ScheduleModule } from '@nestjs/schedule';
// 导入微服务客户端代理相关模块
import { ClientProxyFactory, Transport } from '@nestjs/microservices';
import { APP_GUARD } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { FileModule } from './server/file/file.module';
import { AuthModule } from './server/auth/auth.module';
import { UserModule } from './server/user/user.module';
import { DemoModule } from './server/demo/demo.module';
import mongoConfig from '../../../config/mongo.config';
import { JwtAuthGuard } from '../../../common/auth.guard';
import { MailModule } from './server/mail/mail.module';
import { TaskModule } from './server/task/task.module';
import { WebsocketsModule } from './events/websockets/websockets.module';
import mailConfig from '../../../config/mail.config';

@Module({
  imports: [
    ScheduleModule.forRoot(),
    ConfigModule.forRoot(),
    EventEmitterModule.forRoot(),
    MongooseModule.forRoot(mongoConfig.uri),
    MailerModule.forRoot({
      transport: {
        host: mailConfig.host, //邮箱服务器地址
        port: mailConfig.port, //服务器端口 默认 465
        auth: {
          user: mailConfig.user, //你的邮箱地址
          pass: mailConfig.pass, //授权码
        },
      },
      preview: true, //是否开启预览，开启了这个属性，在调试模式下会自动打开一个网页，预览邮件
      defaults: {
        from: mailConfig.user, //发送人 你的邮箱地址
      },
    }),
    FileModule,
    AuthModule,
    UserModule,
    DemoModule,
    MailModule,
    TaskModule,
    WebsocketsModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    {
      provide: 'testServer', // 定义提供者的别名
      inject: [ConfigService], // 需要注入的依赖
      useFactory: (configService: ConfigService) => {
        // 工厂函数，创建客户端代理
        return ClientProxyFactory.create({
          transport: Transport.TCP, // 使用TCP作为传输方式
          options: {
            host: configService.get('MAIN_APP_HOST'), // 从配置中获取主机地址
            port: configService.get('TEST_APP_PORT'), // 从配置中获取端口号
          },
        });
      },
    },
  ],
})
export class AppModule {}
